< previous page page_292 next page >

Page 292
Luckily, you don't have to actually write all this in a series of SQL statements. You can get the same results by adding the HAVING keyword to the GROUP BY clause. The HAVING clause acts the same as the WHERE clause, except that the HAVING clause acts upon the resulting columns created by the GROUP BY clause, not the underlying columns. The following SQL statement (see Figure 8.26) returns only the Titles that have sold more than 100 units in the last year:
SELECT Title, SUM(Units) AS UnitsSold
   FROM BookSales
   GROUP BY Title HAVING SUM(Units)>100
0292-01.jpg
Figure 8.26.
Using the 
HAVING clause with GROUP BY.
The columns used in the HAVING clause do not have to be the same columns listed in the SELECT clause. The contents of the HAVING clause follow the same rules as those for the contents of the WHERE clause. You can use logical operators AND, OR, and NOT, and you can include VB-specific functions as part of the HAVING clause. The following SQL statement (see Figure 8.27) returns sales in dollars for all titles that have more than 100 units sold and whose titles have the letter a as the second letter in the title:
SELECT Title, SUM(Sales) AS SalesAmt
   FROM BookSales
   GROUP BY Title
   HAVING SUM(Units)>100 AND Mid$(Title,2,1)="a"
0292-02.jpg
Figure 8.27.
Using a complex 
HAVING clause.

 
< previous page page_292 next page >

If you like this book, buy it!